local register = event.register
local unregister = event.unregister
local socket = require("socket")
local copas = require('copas')
require("basicZapper")


server = assert(socket.bind("*", 1212))

print("--------------------------------", server.port)
local typeKey = {'press','release'}
local keyMap = require('keyMap')
local rkeyboard = nil
local rkeyRunning = false
rEdit = nil

local rprint = function (...)
print('=====SecondScreen=====', ...)
end
local handlers = function() return end

event.register = function(...)
rprint('registrei')
handlers = ...
register(...)
end
event.unregister = function (...)
rprint('disregistrei')
handlers =  function() return end
unregister(...)
end


local function secondScreen(key)
	if(key == 'vol_up_rep_end') then
		holdingVolUp = false
	elseif (key == 'vol_down_rep_end') then
		holdingVolDown = false
	end

    if (tonumber(key)) then 
		sendToHandler(key,key)
		return true    
    elseif keyMap[key] then 
        if type(keyMap[key]) == "string" then
			sendToHandler(key)
            return true
        else 
            keyMap[key]()
            return true
        end
    else 
    end
    return false
end

function sendToHandler(echokey,opt )
	if keyRunning and echokey ~= "back" then return end
	handlers ({class = 'key', key = opt or keyMap[echokey], type = typeKey[1] })
	handlers ({class = 'key', key = opt or keyMap[echokey], type = typeKey[2] })
end
function echoHandler(skt)
  while true do
    local data = copas.receive(skt)
    if  not (secondScreen(data)) then
		if rkeyboard and data then
			if(rEdit._password == nil)then
				rEdit:text(data)
				rEdit._cursor = (#data +1)
			else
				rEdit._password =  data
				rEdit._cursor = #data
			end
				rEdit:draw()
				canvas:flush()
		end 
	else
			if (keyRunning) then
				copas.send(skt,'key,'..rEdit:text()..'\n')
			else	
				copas.send(skt, 'recebi '..data..'\n')
			end
	end
 
 end
end

copas.addserver(server, echoHandler, 0.1)

function setKeyboard (keyboarda)
rprint('atribui um teclado = ', type(keyboarda))
rkeyboard = keyboarda
rEdit = rkeyboard._textEdit
end

function openKeyboardOnDivice(bollRunning)
rprint('habilitei o teclado = ', bollRunning)
keyRunning= bollRunning

end
function setEdit(textEdit)
rEdit = textEdit

end
function refreshControl()
	event.timer(200,function()
	copas.step(0.1)
	refreshControl()
end)
end

refreshControl()
